<template>
  <div class="trending-page">
    <div class="content-container">
      <!-- 左侧功能区域 -->
      <div class="left-panel">
        <!-- 楼盘搜索区域 -->
        <div class="search-section">
          <h3>🏢 关联楼盘输入</h3>
          <div class="search-group">
            <input
              v-model="propertySearch"
              type="text"
              placeholder="请输入楼盘名称..."
              class="search-input"
            />
            <!-- <button @click="searchProperty" class="search-btn">🔍 搜索</button> -->
          </div>
        </div>

        <!-- 内容输入区域 -->
        <div class="input-section">
          <h3>📝 内容输入</h3>
          <div class="title-input-group">
            <input
              v-model="titleInput"
              type="text"
              placeholder="请输入标题..."
              class="title-input"
            />
          </div>
          
          <textarea
            v-model="contentInput"
            placeholder="请输入要上传的文章内容"
            class="content-textarea"
            rows="8"
          ></textarea>
        </div>

        <!-- 文件上传区域 -->
        <div class="upload-section">
          <h3>📎 文件上传</h3>
          <div class="upload-buttons">
            <button @click="uploadImage" class="upload-btn image-btn" :disabled="isUploading">
              📷 上传图片
            </button>
            <button @click="uploadLink" class="upload-btn link-btn">
              🔗 上传链接
            </button>
          </div>
          
          <!-- 已上传图片预览 -->
          <div v-if="uploadedImages.length > 0" class="uploaded-images">
            <h4>已上传图片 ({{ uploadedImages.length }})</h4>
            <div class="image-preview-list">
              <div 
                v-for="(image, index) in uploadedImages" 
                :key="index" 
                class="image-preview-item"
              >
                <img 
                  :src="image.url" 
                  :alt="`图片 ${index + 1}`" 
                  class="preview-image"
                  @error="handlePreviewImageError($event, index)"
                />
                <button @click="removeImage(index)" class="remove-image-btn">×</button>
                <div class="image-name">{{ image.name }}</div>
              </div>
            </div>
          </div>
          
          <button @click="startAnalysis" class="analyze-btn" :disabled="!canAnalyze">
            🚀 上传文章
          </button>
        </div>
      </div>

      <!-- 右侧数据展示区域 -->
      <div class="right-panel">
        <!-- 筛选区域 -->
        <div class="filter-section">
          <h3>🔍 筛选条件</h3>
          <div class="filter-row">
            <div class="filter-group">
              <input
                v-model="titleSearch"
                type="text"
                placeholder="搜索标题..."
                class="filter-input"
              />
              <button @click="searchByTitle" class="filter-btn">🔍</button>
            </div>
            
            <div class="filter-group">
              <input
                v-model="startDate"
                type="date"
                class="filter-input"
                @change="onDateChange"
              />
              <span class="filter-label">至</span>
              <input
                v-model="endDate"
                type="date"
                class="filter-input"
                @change="onDateChange"
              />
            </div>
            
            <div class="filter-group">
              <select v-model="sourceFilter" class="filter-select" @change="onSourceChange">
                <option value="">全部来源</option>
                <option value="小红书">小红书</option>
                <option value="微信">微信</option>
                <option value="网站">网站</option>
                <option value="抖音">抖音</option>
                <option value="用户">用户</option>
                <option value="微信社区">微信社区</option>
              </select>
            </div>
            
            <div class="filter-group">
              <select v-model="sortValue" class="filter-select" @change="onSortChange">
                <option value="">默认排序</option>
                <option value="time">按时间排序</option>
                <option value="hot">按热度排序</option>
              </select>
            </div>
            
            <div class="filter-group">
              <input
                v-model="estateSearch"
                type="text"
                placeholder="搜索关联楼盘..."
                class="filter-input"
                @keyup.enter="searchEstate"
              />
              <button @click="searchEstate" class="filter-btn">🔍</button>
            </div>
            
            <div class="filter-group">
              <div class="filter-user-search-wrapper">
                <input
                  v-model="filterUserSearchKeyword"
                  type="text"
                  :placeholder="selectedFilterUser ? selectedFilterUser.name : '搜索用户...'"
                  class="filter-input"
                  @input="searchFilterUsers"
                  @focus="handleFilterUserFocus"
                  @blur="handleFilterUserInputBlur"
                />
                <div class="filter-search-icon">🔍</div>
                <button 
                  v-if="selectedFilterUser" 
                  @click="clearSelectedFilterUser" 
                  class="clear-filter-user-btn"
                  style="position: absolute; right: 25px; top: 50%; transform: translateY(-50%); background: none; border: none; color: #f44336; cursor: pointer; font-size: 14px; padding: 0; width: 16px; height: 16px; display: flex; align-items: center; justify-content: center; border-radius: 50%;"
                >
                  ×
                </button>
                <div v-if="showFilterUserDropdown" class="filter-user-dropdown">
                  <div 
                    v-for="user in filteredFilterUsers" 
                    :key="user.id"
                    class="filter-user-option"
                    @click="selectFilterUser(user)"
                  >
                    {{ user.name }}
                  </div>
                  <div v-if="filteredFilterUsers.length === 0" class="filter-user-option">
                    暂无用户数据
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
          <h3>📊 智能选题数据</h3>
          <div v-if="loading" class="loading-overlay">
            <div class="loading-spinner">加载中...</div>
          </div>
          
          <!-- 弹窗组件 -->
          <div v-if="tooltipVisible" class="tooltip" :style="tooltipStyle">
            <div class="tooltip-content">{{ tooltipText }}</div>
          </div>
          
          <!-- 图片画廊弹窗 -->
          <div v-if="imageGalleryVisible" class="image-gallery-overlay" @click="closeImageGallery">
            <div class="image-gallery-modal" @click.stop>
              <div class="gallery-header">
                <h3>{{ currentGalleryTitle }}</h3>
                <button class="close-btn" @click="closeImageGallery">×</button>
              </div>
              <div class="gallery-content">
                <button 
                  v-if="currentImageIndex > 0" 
                  class="nav-btn prev-btn" 
                  @click="prevImage"
                >
                  ‹
                </button>
                <div class="image-display">
                  <img 
                    :src="createImageWithReferer(currentGalleryImages[currentImageIndex])" 
                    :alt="`图片 ${currentImageIndex + 1}`"
                    class="gallery-image"
                    @error="handleGalleryImageError"
                    @load="handleGalleryImageLoad"
                  />
                                     <div v-if="galleryImageError" class="gallery-error">
                     <div class="error-content">
                       <span class="error-icon">📷</span>
                       <p class="error-text">微信图片无法显示</p>
                       <p class="error-desc">由于微信图片防盗链限制，无法直接访问</p>
                       <p class="error-solution">建议：右键图片链接，在新标签页中打开</p>
                     </div>
                   </div>
                </div>
                <button 
                  v-if="currentImageIndex < currentGalleryImages.length - 1" 
                  class="nav-btn next-btn" 
                  @click="nextImage"
                >
                  ›
                </button>
              </div>
              <div class="gallery-footer">
                <span class="image-counter">{{ currentImageIndex + 1 }} / {{ currentGalleryImages.length }}</span>
                <div class="thumbnail-container">
                  <div 
                    v-for="(image, index) in currentGalleryImages" 
                    :key="index"
                    class="thumbnail"
                    :class="{ active: index === currentImageIndex }"
                    @click="goToImage(index)"
                  >
                    <img :src="createImageWithReferer(image)" :alt="`缩略图 ${index + 1}`" />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="table-container">
            <table class="data-table">
              <thead>
                <tr>
                  <th>标题</th>
                  <th>图片/智能提取</th>
                  <th>内容链接</th>
                  <th>来源</th>
                  <th>创建时间</th>
                  <th>关联楼盘</th>
                  <th>热度值</th>
                  <th>审核状态</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in paginatedData" :key="item.id || index">
                  <td class="title-cell">{{ item.title }}</td>
                  <td class="extract-cell">
                    <div v-if="item.image_url && item.image_url.length > 0" class="image-container" :class="{ loading: item.imageLoading, loaded: item.imageLoaded }">
                      <img 
                        :src="createImageWithReferer(item.image_url[0])" 
                        :alt="item.title"
                        class="extract-image"
                        @click="showImageGallery(item.image_url, item.title)"
                        @error="handleImageError"
                        @load="handleImageLoad"
                      />
                      <div class="image-placeholder" v-if="item.imageError" @click="showImageGallery(item.image_url, item.title)">
                        <span class="placeholder-text">
                          <div class="error-icon-small">📷</div>
                          微信图片无法显示<br>
                          <small>点击尝试查看原图</small>
                        </span>
                        <div class="image-links" v-if="item.image_url && item.image_url.length > 0">
                          <a 
                            :href="item.image_url[0]" 
                            target="_blank" 
                            class="image-link"
                            @click.stop
                          >
                            在新窗口打开
                          </a>
                        </div>
                      </div>
                    </div>
                    <div 
                      v-else
                      class="extract-content"
                      @mouseenter="showTooltip($event, item.ai_content)"
                      @mouseleave="hideTooltip"
                    >
                      {{ truncateContent(item.ai_content) }}
                    </div>
                  </td>
                  <td class="link-cell">
                    <a :href="item.url" target="_blank" class="content-link">
                      🔗 查看
                    </a>
                  </td>
                  <td class="source-cell">
                    <span class="source-tag" :class="getSourceClass(item.from)">
                      {{ getSourceName(item) }}
                    </span>
                  </td>
                  <td class="time-cell">{{ formatTime(item.create_time) }}</td>
                  <td class="property-cell">{{ formatEstateName(item.estate_name) }}</td>
                  <td class="heat-cell">
                    <div class="heat-value">
                      <span class="heat-number">{{ item.hot_num }}</span>
                    </div>
                  </td>
                  <td class="status-cell">
                    <div class="status-buttons">
                      <button 
                        @click="updateArticleStatus(item.id, 1)"
                        class="status-btn correct-btn"
                        :class="{ active: item.is_checked === 1 }"
                        :disabled="loading"
                      >
                        正确
                      </button>
                      <button 
                        @click="updateArticleStatus(item.id, 2)"
                        class="status-btn error-btn"
                        :class="{ active: item.is_checked === 2 }"
                        :disabled="loading"
                      >
                        错误
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 分页控件 -->
          <div class="pagination">
            <button 
              @click="prevPage" 
              :disabled="currentPage === 1"
              class="page-btn"
            >
              ← 上一页
            </button>
            <span class="page-info">
              第 {{ currentPage }} 页，共 {{ totalPages }} 页
            </span>
            <button 
              @click="nextPage" 
              :disabled="currentPage >= totalPages"
              class="page-btn"
            >
              下一页 →
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import axios from 'axios';
import OSS from 'ali-oss';

// 左侧面板数据
const propertySearch = ref('');
const titleInput = ref('');
const contentInput = ref('');
const link = ref('');

// 当前用户信息
const currentUserName = ref('');

// OSS配置
let ossClient = null;
let ossParams = null;

// 获取OSS上传参数
const getOSSParams = async () => {
  try {
    const response = await axios.get('/api/erp/screenshot/data/oss');
    if (response.data && response.data.data) {
      ossParams = response.data.data;
      console.log('获取OSS参数成功:', ossParams);
      return ossParams;
    } else {
      throw new Error('OSS参数响应格式错误');
    }
  } catch (error) {
    console.error('获取OSS参数失败:', error);
    throw error;
  }
};

// 初始化OSS客户端
const initOSSClient = async () => {
  try {
    // 先获取OSS参数
    if (!ossParams) {
      await getOSSParams();
    }
    
    ossClient = new OSS({
      region: 'oss-cn-hangzhou',
      accessKeyId: ossParams.OSSAccessKeyId,
      accessKeySecret: '8jPhIKCqdJ0DWe0RYiEyFsjIKVlI70',
      internal: false,
      bucket: 'xiaoji-hangzhou',
      timeout: 60000, // 60秒超时
      secure: true, // 使用HTTPS
      cname: false, // 不使用自定义域名
      retryMax: 3, // 最大重试次数
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization'
      }
    });
    console.log('OSS客户端初始化成功');
  } catch (error) {
    console.error('OSS客户端初始化失败:', error);
  }
};

const ossBaseUrl = 'https://xiaoji-hangzhou.oss-cn-hangzhou.aliyuncs.com/img/';

// 上传的图片列表
const uploadedImages = ref([]);
const isUploading = ref(false);

// 右侧筛选数据
const titleSearch = ref('');
const startDate = ref('');
const endDate = ref('');
const sourceFilter = ref('');
const sortValue = ref('');
const estateSearch = ref('');
const userNameSearch = ref('');

// 筛选用户搜索相关数据
const filterUserSearchKeyword = ref('');
const filteredFilterUsers = ref([]);
const selectedFilterUser = ref(null);
const showFilterUserDropdown = ref(false);

// API配置
const API_ENDPOINT = '/media/article/search/hot/topic/list';

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);

// 加载状态
const loading = ref(false);

// 弹窗状态
const tooltipVisible = ref(false);
const tooltipText = ref('');
const tooltipStyle = ref({
  left: '0px',
  top: '0px'
});

// 图片画廊状态
const imageGalleryVisible = ref(false);
const currentGalleryImages = ref([]);
const currentImageIndex = ref(0);
const currentGalleryTitle = ref('');
const galleryImageError = ref(false);

// 获取最近一周的日期范围
const getLastWeekRange = () => {
  const end = new Date();
  const start = new Date();
  start.setDate(start.getDate() - 7);
  
  return {
    start: start.toISOString().split('T')[0], // 格式：2025-01-07
    end: end.toISOString().split('T')[0]
  };
};

// 模拟数据
const tableData = ref([]);

// 计算属性
const canAnalyze = computed(() => {
  if (uploadedImages.value.length > 0 || link.value.trim() !== '') {
    return true;
  }
  return propertySearch.value.trim() || titleInput.value.trim() || contentInput.value.trim();
});

// 总页数
const totalPages = ref(0);

// 直接使用API返回的数据，不需要前端分页
const paginatedData = computed(() => {
  return tableData.value;
});

// API请求方法
const fetchHotTopics = async (params = {}) => {
  try {
    loading.value = true;
    
    // 构建请求参数
    const requestParams = {
      page: params.page || currentPage.value,
      limit: pageSize.value,
      keyword: params.keyword || titleSearch.value,
      estate_name: params.estate_name || estateSearch.value,
      from_source: params.from_source || sourceFilter.value,
      sort: params.sort || sortValue.value,
      start_time: params.start_time || startDate.value,
      end_time: params.end_time || endDate.value,
      user_name: params.user_name || (selectedFilterUser.value ? selectedFilterUser.value.name : '')
    };

    if (requestParams.from_source === '全部来源') {
      delete requestParams.from_source;
    }
    
    // 移除空值参数
    Object.keys(requestParams).forEach(key => {
      if (!requestParams[key]) {
        delete requestParams[key];
      }
    });
    
    const response = await axios.post(`${API_ENDPOINT}`, requestParams, {
      headers: {
        'Content-Type': 'application/json',  // 明确指定 JSON 格式
      },
    });
    
    if (response.data && response.data.success) {
      // 更新表格数据
      let temp_list = response.data.data || [];
      for (const item of temp_list) {
        if (item.image_url) {
          try {
            // 检查是否已经是数组格式
            if (Array.isArray(item.image_url)) {
              // 已经是数组，直接使用
              console.log('图片URL已经是数组格式:', item.image_url);
            } else if (typeof item.image_url === 'string') {
              // 处理Python列表格式的字符串，如 "['http://example.com']"
              let urlString = item.image_url;
              if (urlString.startsWith('[') && urlString.endsWith(']')) {
                // 移除首尾的方括号，然后按逗号分割
                urlString = urlString.slice(1, -1);
                // 分割字符串并清理引号
                let urls = urlString.split(',').map(url => {
                  url = url.trim();
                  // 移除单引号或双引号
                  if ((url.startsWith("'") && url.endsWith("'")) || 
                      (url.startsWith('"') && url.endsWith('"'))) {
                    url = url.slice(1, -1);
                  }
                  return url;
                }).filter(url => url.length > 0);
                item.image_url = urls;
              } else {
                // 尝试JSON解析
                let urls = JSON.parse(item.image_url);
                item.image_url = urls;
              }
            } else {
              // 其他格式，设置为空数组
              item.image_url = [];
            }
          } catch (error) {
            console.error('解析图片URL失败:', error, '原始数据:', item.image_url);
            item.image_url = [];
          }
        } else {
          // 如果没有image_url字段，设置为空数组
          item.image_url = [];
        }
        
        // 设置图片加载状态
        if (item.image_url && item.image_url.length > 0) {
          item.imageLoading = true;
          item.imageLoaded = false;
          item.imageError = false;
        }
      }
      tableData.value = temp_list;
      totalPages.value = (Math.ceil(response.data.total_count / pageSize.value)) || 0;
    } else {
      console.error('API请求失败:', response.data);
    }
  } catch (error) {
    console.error('请求出错:', error);
    // 如果API请求失败，使用模拟数据
    console.log('使用模拟数据');
  } finally {
    loading.value = false;
  }
};

// 初始化数据
const initData = () => {
  const { start, end } = getLastWeekRange();
  startDate.value = start;
  endDate.value = end;
  console.log('初始化时间范围:', start, '到', end);
  fetchHotTopics();
};

// 点击外部关闭下拉框
const handleClickOutside = (event) => {
  const filterUserSearchGroup = event.target.closest('.filter-group');
  
  if (!filterUserSearchGroup) {
    showFilterUserDropdown.value = false;
  }
};

// 组件挂载时添加事件监听
onMounted(() => {
  document.addEventListener('click', handleClickOutside);
  initData();
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});


const uploadImage = async () => {
  // 初始化OSS客户端
  if (!ossClient) {
    await initOSSClient();
  }
  
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.multiple = true; // 支持多选
  input.onchange = async (e) => {
    const files = Array.from(e.target.files);
    if (files.length === 0) return;
    
    
    isUploading.value = true;
    
    try {
      const uploadPromises = files.map(file => uploadSingleImage(file));
      const results = await Promise.all(uploadPromises);
      
      
      const ossUploaded = uploadedImages.value.filter(img => img.uploaded).length;
      const localSaved = uploadedImages.value.filter(img => !img.uploaded).length;
      
      let message = `成功处理 ${files.length} 张图片`;
      if (ossUploaded > 0) {
        message += `，其中 ${ossUploaded} 张上传到阿里云OSS`;
      }
      if (localSaved > 0) {
        message += `，${localSaved} 张保存为本地预览`;
      }
      
    } catch (error) {
      console.error('图片上传失败:', error);
      let errorMessage = '图片上传失败';
      
      if (error.code === 'AccessDenied') {
        errorMessage = '访问被拒绝，请检查OSS配置';
      } else if (error.code === 'NoSuchBucket') {
        errorMessage = '存储桶不存在';
      } else if (error.code === 'InvalidAccessKeyId') {
        errorMessage = 'AccessKey无效';
      } else if (error.message) {
        errorMessage += ': ' + error.message;
      }
      
      alert(errorMessage);
    } finally {
      isUploading.value = false;
    }
  };
  input.click();
};

// 上传单张图片到OSS
const uploadSingleImage = async (file) => {
  try {
    // 检查OSS客户端是否初始化
    if (!ossClient) {
      await initOSSClient();
      if (!ossClient) {
        throw new Error('OSS客户端初始化失败');
      }
    }
    
    console.log('开始上传文件:', file.name, '大小:', file.size);
    
    // 生成唯一的文件名
    const timestamp = Date.now();
    const randomStr = Math.random().toString(36).substring(2, 8);
    const fileExtension = file.name.split('.').pop();
    const fileName = `img/${timestamp}_${randomStr}.${fileExtension}`;
    
    console.log('生成的文件名:', fileName);
    
    // 创建本地预览URL（base64）
    const reader = new FileReader();
    const previewPromise = new Promise((resolve, reject) => {
      reader.onload = (e) => resolve(e.target.result);
      reader.onerror = (e) => reject(e);
      reader.readAsDataURL(file);
    });
    const previewUrl = await previewPromise;
    
    try {
      // 使用从接口获取的参数生成预签名URL
      if (!ossParams) {
        await getOSSParams();
      }
      
      // 构建表单数据
      const formData = new FormData();
      formData.append('key', fileName);
      formData.append('policy', ossParams.policy);
      formData.append('OSSAccessKeyId', ossParams.OSSAccessKeyId);
      formData.append('signature', ossParams.signature);
      formData.append('success_action_status', '200');
      formData.append('file', file);
      
      // 直接上传到OSS
      const ossUploadResponse = await fetch('https://xiaoji-hangzhou.oss-cn-hangzhou.aliyuncs.com', {
        method: 'POST',
        body: formData
      });
      
      if (ossUploadResponse.ok) {
        const finalUrl = `https://xiaoji-hangzhou.oss-cn-hangzhou.aliyuncs.com/${fileName}`;
        console.log('OSS表单上传成功:', finalUrl);
        
        // 添加到已上传图片列表
        uploadedImages.value.push({
          name: file.name,
          url: previewUrl, // 使用base64预览
          ossKey: fileName,
          originalUrl: finalUrl,
          uploaded: true
        });
        
        return finalUrl;
      } else {
        throw new Error(`OSS表单上传失败: ${ossUploadResponse.status} ${ossUploadResponse.statusText}`);
      }
    } catch (ossError) {
      console.error('OSS表单上传失败:', ossError);
      
      // 尝试直接OSS上传
      try {
        const result = await ossClient.put(fileName, file, {
          timeout: 60000,
          headers: {
            'Content-Type': file.type
          }
        });
        
        console.log('直接OSS上传成功:', result.url);
        
        uploadedImages.value.push({
          name: file.name,
          url: previewUrl,
          ossKey: fileName,
          originalUrl: result.url,
          uploaded: true
        });
        
        return result.url;
      } catch (directError) {
        console.error('直接OSS上传也失败:', directError);
        
        // 最后使用base64
        uploadedImages.value.push({
          name: file.name,
          url: previewUrl,
          ossKey: fileName,
          originalUrl: previewUrl,
          uploaded: false
        });
        
        console.log('所有OSS上传方式失败，使用base64存储');
        return previewUrl;
      }
    }
  } catch (error) {
    console.error('单张图片处理失败:', error);
    console.error('错误详情:', {
      message: error.message,
      code: error.code,
      requestId: error.requestId,
      hostId: error.hostId
    });
    throw error;
  }
};

// 移除已上传的图片
const removeImage = (index) => {
  uploadedImages.value.splice(index, 1);
};

// 处理预览图片加载错误
const handlePreviewImageError = (event, index) => {
  const image = uploadedImages.value[index];
  if (image && image.originalUrl) {
    // 如果base64预览失败，尝试使用代理服务
    const proxyUrl = `https://images.weserv.nl/?url=${encodeURIComponent(image.originalUrl)}`;
    event.target.src = proxyUrl;
  }
};

const uploadLink = () => {
  const link_url = prompt('请输入链接地址:(支持小红书，微信文章)');
  if (link_url) {
    link.value = link_url;
  }
};

const startAnalysis = async () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以要 +1
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

  if ( !currentUserName.value ) {
    alert('用户信息获取失败，请重新登录');
    return;
  }

  // 显示临时弹窗
  const tempModal = document.createElement('div');
  tempModal.style.cssText = `
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 20px 30px;
    border-radius: 8px;
    font-size: 16px;
    z-index: 9999;
    display: flex;
    align-items: center;
    gap: 10px;
  `;
  tempModal.innerHTML = `
    <div style="width: 20px; height: 20px; border: 2px solid #fff; border-top: 2px solid transparent; border-radius: 50%; animation: spin 1s linear infinite;"></div>
    <span>正在上传文章，请稍候... 弹窗持续10s后自动关闭</span>
  `;
  
  // 添加旋转动画样式
  const style = document.createElement('style');
  style.textContent = `
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  `;
  document.head.appendChild(style);
  document.body.appendChild(tempModal);

  // 3秒后自动关闭弹窗
  setTimeout(() => {
    document.body.removeChild(tempModal);
    document.head.removeChild(style);
  }, 10000);

  // 获取上传的图片URL列表（使用原始URL）
  const imageUrls = uploadedImages.value.map(img => img.originalUrl);
  
  let requestParams ={
    article_list: [
        {
        title: titleInput.value,
        content: contentInput.value,
        from: '用户',
        estate_name: [propertySearch.value],
        url: link.value,
        image_url: imageUrls, // 添加图片URL数组
        user_name: currentUserName.value, // 使用当前登录用户名
        create_time: formattedTime
      }
    ]
  }
  const response = await axios.post(`/media/article/save/article`, requestParams, {
      headers: {
        'Content-Type': 'application/json',  // 明确指定 JSON 格式
      },
    });
  if (response.data && response.data.success) {
    console.log('上传成功', response.data);

  } else {
    console.error('上传失败:', response.data);
    alert('上传失败');
  }
  link.value = '';
  titleInput.value = '';
  contentInput.value = '';
  uploadedImages.value = [];
};

const searchByTitle = () => {
  console.log('按标题搜索:', titleSearch.value);
  currentPage.value = 1;
  fetchHotTopics({
    keyword: titleSearch.value,
    page: 1
  });
};

// 日期变化处理
const onDateChange = () => {
  // 只有当开始时间和结束时间都设置了才触发搜索
  if (startDate.value && endDate.value) {
    console.log('日期范围变化，重新搜索:', startDate.value, '至', endDate.value);
    currentPage.value = 1;
    fetchHotTopics({
      start_time: startDate.value,
      end_time: endDate.value,
      page: 1
    });
  }
};

// 来源变化处理
const onSourceChange = () => {
  console.log('来源筛选变化，重新搜索:', sourceFilter.value);
  currentPage.value = 1;
  fetchHotTopics({
    from_source: sourceFilter.value,
    page: 1
  });
};

// 排序变化处理
const onSortChange = () => {
  console.log('排序方式变化，重新搜索:', sortValue.value);
  currentPage.value = 1;
  fetchHotTopics({
    sort: sortValue.value,
    page: 1
  });
};

// 楼盘搜索处理
const searchEstate = () => {
  console.log('楼盘搜索:', estateSearch.value);
  currentPage.value = 1;
  fetchHotTopics({
    estate_name: estateSearch.value,
    page: 1
  });
};

// 筛选用户搜索相关方法
const searchFilterUsers = async () => {
  // 如果当前有选中的用户，不进行搜索
  if (selectedFilterUser.value) {
    return;
  }
  
  if (!filterUserSearchKeyword.value.trim()) {
    // 如果搜索关键词为空，显示所有用户
    filteredFilterUsers.value = userList.value;
    return;
  }
  
  try {
    const response = await axios.post('/api/erp/test/search/user', {
      search: filterUserSearchKeyword.value
    });
    
    if (response.data && response.data.success && response.data.list) {
      filteredFilterUsers.value = response.data.list;
      console.log('筛选用户搜索结果:', filteredFilterUsers.value);
    } else {
      filteredFilterUsers.value = [];
    }
  } catch (error) {
    console.error('筛选用户搜索失败:', error);
    filteredFilterUsers.value = [];
  }
};

// 选择筛选用户
const selectFilterUser = (user) => {
  selectedFilterUser.value = user;
  filterUserSearchKeyword.value = user.name; // 将选中的用户名显示在输入框中
  showFilterUserDropdown.value = false;
  console.log('选择筛选用户:', user);
  
  // 自动触发搜索
  currentPage.value = 1;
  fetchHotTopics({
    user_name: user.name,
    page: 1
  });
};

// 处理筛选用户输入框获得焦点
const handleFilterUserFocus = () => {
  console.log('筛选用户输入框获得焦点');
  showFilterUserDropdown.value = true;
  // 如果当前有选中的用户，清空搜索关键词以显示所有用户
  if (selectedFilterUser.value) {
    filterUserSearchKeyword.value = '';
  }
  // 确保有用户数据可以显示
  if (filteredFilterUsers.value.length === 0) {
    filteredFilterUsers.value = userList.value;
  }
  console.log('showFilterUserDropdown:', showFilterUserDropdown.value);
  console.log('filteredFilterUsers:', filteredFilterUsers.value);
};

// 处理筛选用户输入框失焦
const handleFilterUserInputBlur = () => {
  // 延迟关闭下拉框，让点击事件先执行
  setTimeout(() => {
    showFilterUserDropdown.value = false;
  }, 200);
};

// 清除选中的筛选用户
const clearSelectedFilterUser = () => {
  selectedFilterUser.value = null;
  filterUserSearchKeyword.value = '';
  console.log('清除选中筛选用户');
  
  // 重新搜索，不包含用户筛选
  currentPage.value = 1;
  fetchHotTopics({ page: 1 });
};

// 获取当前用户信息
const getCurrentUserInfo = () => {
  try {
    const userInfoStr = sessionStorage.getItem('user_info');
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr);
      currentUserName.value = userInfo.name || userInfo.username || '';
      console.log('获取当前用户信息:', currentUserName.value);
    } else {
      currentUserName.value = '';
      console.log('未找到用户信息');
    }
  } catch (error) {
    console.error('解析用户信息失败:', error);
    currentUserName.value = '';
  }
};



const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchHotTopics({ page: currentPage.value });
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchHotTopics({ page: currentPage.value });
  }
};

const getSourceClass = (source) => {
  const classes = {
    '小红书': 'source-xiaohongshu',
    '微信': 'source-wechat',
    '网站': 'source-website',
    '抖音': 'source-douyin',
    '用户': 'source-user',
    '微信社区': 'source-wechat-community'
  };
  return classes[source] || 'source-default';
};

const getSourceName = (source) => {
  if (source.user_name) {
    return source.user_name;
  }
  return source.from || '未知';
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  return timeStr.split(' ')[0]; // 只显示日期部分
};

// 格式化楼盘名称
const formatEstateName = (estateArray) => {
  if (!estateArray || !Array.isArray(estateArray) || estateArray.length === 0) {
    return '未关联楼盘';
  }
  return estateArray.join(', ');
};







// 更新文章状态
const updateArticleStatus = async (articleId, newStatus) => {
  try {
    loading.value = true;
    console.log('更新文章状态:', articleId, newStatus);
    const response = await axios.post(`/media/article/update/article/status`, {
      article_id: articleId,
      status: newStatus
    }, {
      timeout: 10000
    });
    
    if (response.data && response.data.success) {
      // 更新本地数据
      const article = tableData.value.find(item => item.id === articleId);
      if (article) {
        article.is_checked = newStatus;
      }
      console.log('状态更新成功');
    } else {
      console.error('状态更新失败:', response.data);
    }
  } catch (error) {
    console.error('更新状态出错:', error);
  } finally {
    loading.value = false;
  }
};

// 截断内容显示
const truncateContent = (content) => {
  if (!content) return '';
  const lines = content.split('\n');
  if (lines.length <= 5) return content;
  return lines.slice(0, 5).join('\n') + '\n...';
};

// 显示弹窗
const showTooltip = (event, content) => {
  if (!content) return;
  
  const rect = event.target.getBoundingClientRect();
  const tableRect = event.target.closest('.table-container').getBoundingClientRect();
  
  tooltipText.value = content;
  tooltipStyle.value = {
    left: `${rect.left - tableRect.left + rect.width / 2}px`,
    top: `${rect.top - tableRect.top - 10}px`
  };
  tooltipVisible.value = true;
};

// 隐藏弹窗
const hideTooltip = () => {
  tooltipVisible.value = false;
};

// 显示图片画廊
const showImageGallery = (images, title) => {
  if (!images || images.length === 0) return;
  
  currentGalleryImages.value = images;
  currentImageIndex.value = 0;
  currentGalleryTitle.value = title;
  imageGalleryVisible.value = true;
  galleryImageError.value = false; // 重置错误状态
  
  // 阻止页面滚动
  document.body.style.overflow = 'hidden';
};

// 关闭图片画廊
const closeImageGallery = () => {
  imageGalleryVisible.value = false;
  // 恢复页面滚动
  document.body.style.overflow = 'auto';
};

// 上一张图片
const prevImage = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--;
    galleryImageError.value = false; // 重置错误状态
  }
};

// 下一张图片
const nextImage = () => {
  if (currentImageIndex.value < currentGalleryImages.value.length - 1) {
    currentImageIndex.value++;
    galleryImageError.value = false; // 重置错误状态
  }
};

// 跳转到指定图片
const goToImage = (index) => {
  currentImageIndex.value = index;
  galleryImageError.value = false; // 重置错误状态
};

// 处理图片加载成功
const handleImageLoad = (event) => {
  // 确保图片可见
  event.target.style.display = 'block';
  
  // 找到对应的数据项并更新状态
  const item = tableData.value.find(item => 
    item.image_url && item.image_url.some(url => event.target.src.includes(url))
  );
  if (item) {
    item.imageError = false;
    item.imageLoading = false;
    item.imageLoaded = true;
  }
  
  // 移除加载动画
  const container = event.target.closest('.image-container');
  if (container) {
    container.classList.remove('loading');
    container.classList.add('loaded');
  }
};

// 处理图片加载错误
const handleImageError = (event) => {
  const img = event.target;
  const currentSrc = img.src;
  
  // 找到对应的数据项
  const item = tableData.value.find(item => 
    item.image_url && item.image_url.some(url => currentSrc.includes(url))
  );
  
  // 检查是否是微信图片
  if (currentSrc.includes('mmbiz.qpic.cn')) {
    // 如果当前使用的是weserv代理，尝试原始URL
    if (currentSrc.includes('images.weserv.nl/')) {
      const originalUrl = decodeURIComponent(currentSrc.split('url=')[1].split('&')[0]);
      console.log('weserv代理失败，尝试原始URL:', originalUrl);
      img.src = originalUrl;
      return;
    }
    // 如果当前是allorigins代理，尝试原始URL
    else if (currentSrc.includes('api.allorigins.win/')) {
      const originalUrl = decodeURIComponent(currentSrc.split('url=')[1].split('&')[0]);
      console.log('allorigins代理失败，尝试原始URL:', originalUrl);
      img.src = originalUrl;
      return;
    }
    // 如果当前是原始URL，尝试多个代理
    else {
      // 尝试多个代理服务
      const proxyServices = [
        `https://api.allorigins.win/raw?url=${encodeURIComponent(currentSrc)}`,
        `https://images.weserv.nl/?url=${encodeURIComponent(currentSrc)}`,
        `https://cors-anywhere.herokuapp.com/${currentSrc}`,
        `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(currentSrc)}`
      ];
      
      // 随机选择一个代理
      const randomProxy = proxyServices[Math.floor(Math.random() * proxyServices.length)];
      console.log('原始URL失败，尝试代理:', randomProxy);
      img.src = randomProxy;
      return;
    }
  }
  
  // 如果所有尝试都失败了，隐藏图片并显示错误
  img.style.display = 'none';
  if (item) {
    item.imageError = true;
    item.imageLoading = false;
  }
};



// 处理画廊图片加载错误
const handleGalleryImageError = (event) => {
  const img = event.target;
  const currentSrc = img.src;
  
  // 检查是否是微信图片
  if (currentSrc.includes('mmbiz.qpic.cn')) {
    // 如果当前使用的是weserv代理，尝试原始URL
    if (currentSrc.includes('images.weserv.nl/')) {
      const originalUrl = decodeURIComponent(currentSrc.split('url=')[1].split('&')[0]);
      console.log('画廊weserv代理失败，尝试原始URL:', originalUrl);
      img.src = originalUrl;
      return;
    }
    // 如果当前是allorigins代理，尝试原始URL
    else if (currentSrc.includes('api.allorigins.win/')) {
      const originalUrl = decodeURIComponent(currentSrc.split('url=')[1].split('&')[0]);
      console.log('画廊allorigins代理失败，尝试原始URL:', originalUrl);
      img.src = originalUrl;
      return;
    }
    // 如果当前是原始URL，尝试多个代理
    else {
      // 尝试多个代理服务
      const proxyServices = [
        `https://api.allorigins.win/raw?url=${encodeURIComponent(currentSrc)}`,
        `https://images.weserv.nl/?url=${encodeURIComponent(currentSrc)}`,
        `https://cors-anywhere.herokuapp.com/${currentSrc}`,
        `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(currentSrc)}`
      ];
      
      // 随机选择一个代理
      const randomProxy = proxyServices[Math.floor(Math.random() * proxyServices.length)];
      console.log('画廊原始URL失败，尝试代理:', randomProxy);
      img.src = randomProxy;
      return;
    }
  }
  
  // 如果所有尝试都失败了，显示错误
  img.style.display = 'none';
  galleryImageError.value = true;
};

// 处理画廊图片加载成功
const handleGalleryImageLoad = (event) => {
  event.target.style.display = 'block';
  galleryImageError.value = false;
};

// 处理微信图片URL
const processWechatImageUrl = (url) => {
  if (url.includes('mmbiz.qpic.cn')) {
    // 为微信图片添加必要的参数
    const separator = url.includes('?') ? '&' : '?';
    return `${url}${separator}wxfrom=5&wx_lazy=1&tp=webp`;
  }
  return url;
};

// 创建带Referer的图片URL（通过代理或添加请求头）
const createImageWithReferer = (url) => {
  if (!url) return '';
  
  if (url.includes('mmbiz.qpic.cn')) {
    // 为微信图片使用智能代理选择
    const proxyServices = [
      `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`,
      `https://images.weserv.nl/?url=${encodeURIComponent(url)}`,
      `https://cors-anywhere.herokuapp.com/${url}`,
      `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(url)}`
    ];
    
    // 根据URL特征选择最合适的代理
    if (url.includes('wxfrom=5')) {
      return proxyServices[0]; // allorigins对微信图片支持较好
    } else {
      return proxyServices[1]; // weserv对一般图片支持较好
    }
  }
  
  // 如果是阿里云OSS图片，使用代理服务
  if (url.includes('xiaoji-hangzhou.oss-cn-hangzhou.aliyuncs.com')) {
    return `https://images.weserv.nl/?url=${encodeURIComponent(url)}`;
  }
  
  // 其他图片直接返回原URL
  return url;
};



// 页面加载时初始化数据
onMounted(() => {
  console.log('页面加载，开始初始化数据...');
  initOSSClient(); // 初始化OSS客户端
  getCurrentUserInfo(); // 获取当前用户信息
});
</script>

<style scoped>
.trending-page {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--panel-bg-color);
  border-radius: 12px;
  overflow: visible;
}



.content-container {
  flex: 1;
  display: flex;
  min-height: 800px;
}

/* 左侧面板样式 */
.left-panel {
  width: 25%;
  padding: 24px;
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  gap: 24px;
  background: #fafbfc;
  overflow: visible;
}

.left-panel h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: var(--text-color);
  font-weight: 600;
}

.title-input-group {
  margin-bottom: 16px;
}

.title-input {
  width: 100%;
  padding: 12px;
  border: 2px solid var(--border-color);
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.title-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

/* 当前用户信息样式 */
.current-user-info {
  margin-bottom: 16px;
  padding: 12px;
  background: #e3f2fd;
  border: 2px solid #2196f3;
  border-radius: 8px;
}

.current-user-name {
  font-size: 14px;
  color: #1976d2;
  font-weight: 500;
}

.search-group {
  display: flex;
  gap: 8px;
}

.search-input {
  flex: 1;
  padding: 12px;
  border: 2px solid var(--border-color);
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

.search-btn {
  padding: 12px 16px;
  background: var(--primary-color);
  color: var(--text-color);
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.search-btn:hover {
  background: var(--primary-hover);
  transform: translateY(-1px);
}

.content-textarea {
  width: 100%;
  padding: 12px;
  border: 2px solid var(--border-color);
  border-radius: 8px;
  font-size: 14px;
  font-family: inherit;
  resize: vertical;
  min-height: 500px;
  transition: border-color 0.3s ease;
}

.content-textarea:focus {
  outline: none;
  border-color: var(--primary-color);
}

.upload-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.upload-btn {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid var(--border-color);
  border-radius: 8px;
  background: white;
  color: var(--text-color);
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-btn:hover {
  border-color: var(--primary-color);
  background: #f8f9fa;
}

.analyze-btn {
  width: 100%;
  padding: 16px;
  background: var(--primary-color);
  color: var(--text-color);
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.analyze-btn:hover:not(:disabled) {
  background: var(--primary-hover);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(253, 216, 53, 0.3);
}

.analyze-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 已上传图片预览样式 */
.uploaded-images {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.uploaded-images h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: var(--text-color);
  font-weight: 600;
}

.image-preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.image-preview-item {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #e9ecef;
  background: white;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image-btn {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 20px;
  height: 20px;
  border: none;
  border-radius: 50%;
  background: #dc3545;
  color: white;
  font-size: 12px;
  font-weight: bold;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.remove-image-btn:hover {
  background: #c82333;
  transform: scale(1.1);
}

.image-name {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 10px;
  padding: 2px 4px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 右侧面板样式 */
.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  overflow: visible;
}

.filter-section {
  padding: 20px 24px;
  border-bottom: 1px solid var(--border-color);
  background: #fafbfc;
}

.filter-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: var(--text-color);
  font-weight: 600;
}

.filter-row {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
}

.filter-input {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.filter-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

.filter-btn {
  padding: 8px 12px;
  background: var(--primary-color);
  color: var(--text-color);
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.filter-btn:hover {
  background: var(--primary-hover);
}

.filter-label {
  font-size: 14px;
  color: var(--text-color);
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  font-size: 14px;
  background: white;
  cursor: pointer;
}

/* 筛选用户搜索样式 */
.filter-user-search-wrapper {
  position: relative;
  display: inline-block;
}

.filter-search-icon {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  color: #6c757d;
  font-size: 12px;
  pointer-events: none;
}

.filter-user-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid var(--border-color);
  border-top: none;
  border-radius: 0 0 6px 6px;
  max-height: 150px;
  overflow-y: auto;
  z-index: 9999;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  min-width: 150px;
  /* 调试样式 */
  border: 2px solid f0f0f0 !important;
}

.filter-user-option {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s ease;
  border-bottom: 1px solid #f0f0f0;
  font-size: 13px;
}

.filter-user-option:hover {
  background-color: #f8f9fa;
}

.filter-user-option:last-child {
  border-bottom: none;
}

.selected-filter-user {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 8px;
  background: #e3f2fd;
  border: 1px solid #2196f3;
  border-radius: 4px;
  margin-top: 4px;
  font-size: 12px;
}

.selected-filter-user-name {
  font-size: 12px;
  color: #1976d2;
  font-weight: 500;
}

.clear-filter-user-btn {
  background: none;
  border: none;
  color: #f44336;
  cursor: pointer;
  font-size: 14px;
  padding: 0;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s ease;
}

.clear-filter-user-btn:hover {
  background-color: #ffebee;
}

/* 表格区域样式 */
.table-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: visible;
}

.table-section h3 {
  margin: 0;
  padding: 20px 24px 16px;
  font-size: 16px;
  color: var(--text-color);
  font-weight: 600;
  border-bottom: 1px solid var(--border-color);
}

.table-container {
  flex: 1;
  overflow: auto;
  padding: 0 24px;
  max-height: 900px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
  position: relative;
}

.data-table th {
  background: #f8f9fa;
  padding: 12px 8px;
  text-align: center;
  font-weight: 600;
  color: var(--text-color);
  border-bottom: 2px solid var(--border-color);
  position: sticky;
  top: 0;
  z-index: 10;
}

.data-table td {
  padding: 16px 8px;
  border-bottom: 1px solid #e9ecef;
  vertical-align: middle;
  text-align: center;
}

.data-table tr:hover {
  background: #f8f9fa;
}

.title-cell {
  max-width: 150px;
  font-weight: 600;
  text-align: center;
}

.extract-cell {
  max-width: 300px;
  color: #6c757d;
}

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  position: relative;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  overflow: hidden;
}

.image-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  animation: shimmer 1.5s infinite;
}

.image-container.loading::before {
  animation: shimmer 1.5s infinite;
}

.image-container.loaded::before {
  display: none;
}

.extract-image {
  max-width: 100%;
  max-height: 80px;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  position: relative;
  z-index: 1;
}

.extract-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 80px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 2px dashed #dee2e6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.image-placeholder::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.image-placeholder:hover::before {
  left: 100%;
}

.image-placeholder:hover {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
  border-color: #adb5bd;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.placeholder-text {
  font-size: 11px;
  color: #6c757d;
  text-align: center;
  line-height: 1.4;
  z-index: 1;
  position: relative;
}

.error-icon-small {
  font-size: 18px;
  margin-bottom: 4px;
  display: block;
  opacity: 0.7;
}

.placeholder-text small {
  font-size: 9px;
  color: #adb5bd;
  display: block;
  margin-top: 2px;
}

.image-links {
  margin-top: 6px;
  display: flex;
  gap: 4px;
  justify-content: center;
}

.image-link {
  font-size: 9px;
  color: #007bff;
  text-decoration: none;
  padding: 2px 6px;
  border: 1px solid #007bff;
  border-radius: 4px;
  background: rgba(0, 123, 255, 0.1);
  transition: all 0.3s ease;
  white-space: nowrap;
}

.image-link:hover {
  background: #007bff;
  color: white;
  text-decoration: none;
  transform: scale(1.05);
}

.extract-content {
  max-height: 120px;
  overflow: hidden;
  line-height: 1.4;
  cursor: pointer;
  white-space: pre-line;
}

.content-link {
  color: var(--text-secondary);
  text-decoration: none;
  font-weight: 600;
}

.content-link:hover {
  text-decoration: underline;
}

.source-tag {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  color: white;
}

.source-xiaohongshu { background: #ff2442; }
.source-wechat { background: #27ae60; }
.source-website { background: #3498db; }
.source-douyin { background: #615b5c; }
.source-user { background: #9b59b6; }
.source-default { background: #6c757d; }
.source-wechat-community { background: #1e502a; }

.time-cell {
  color: #6c757d;
  font-size: 13px;
}

.property-cell {
  font-weight: 600;
  color: var(--text-secondary);
  max-width: 150px;
}

.heat-value {
  display: flex;
  align-items: center;
  justify-content: center;
}

.heat-number {
  font-size: 14px;
  font-weight: 600;
  color: #e74c3c;
  background: #fdf2f2;
  padding: 4px 8px;
  border-radius: 4px;
}

.status-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.status-btn {
  padding: 6px 12px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 50px;
  background: white;
  color: #6c757d;
}

.status-btn:hover:not(:disabled) {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.status-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.correct-btn.active {
  background: #28a745;
  color: white;
  border-color: #28a745;
}

.error-btn.active {
  background: #dc3545;
  color: white;
  border-color: #dc3545;
}

/* 是否采用按钮样式 */
.adopt-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.adopt-btn {
  padding: 6px 12px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 50px;
  background: white;
  color: #6c757d;
}

.adopt-btn:hover:not(:disabled) {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.adopt-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.adopt-yes-btn.active {
  background: #28a745;
  color: white;
  border-color: #28a745;
}

.adopt-no-btn.active {
  background: #dc3545;
  color: white;
  border-color: #dc3545;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  border-top: 1px solid var(--border-color);
  background: #fafbfc;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background: white;
  color: var(--text-color);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-btn:hover:not(:disabled) {
  background: var(--primary-hover);
  color: var(--text-color);
  border-color: var(--primary-hover);
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: var(--text-color);
}

/* 加载状态样式 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  font-size: 16px;
  color: var(--primary-color);
}

.table-section {
  position: relative;
}

/* 弹窗样式 */
.tooltip {
  position: absolute;
  z-index: 1000;
  background: rgba(0, 0, 0, 0.9);
  color: white;
  padding: 12px;
  border-radius: 8px;
  max-width: 400px;
  max-height: 300px;
  overflow-y: auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-line;
  transform: translateX(-50%);
}

.tooltip-content {
  word-break: break-word;
}

/* 图片画廊弹窗样式 */
.image-gallery-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
  padding: 20px;
}

.image-gallery-modal {
  background: white;
  border-radius: 12px;
  max-width: 90vw;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.gallery-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e9ecef;
  background: #f8f9fa;
}

.gallery-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--text-color);
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #6c757d;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.3s ease;
}

.close-btn:hover {
  background: #e9ecef;
}

.gallery-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  min-height: 400px;
  background: #f8f9fa;
}

.nav-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.9);
  border: none;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  font-size: 24px;
  color: var(--text-color);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  z-index: 10;
}

.nav-btn:hover {
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.prev-btn {
  left: 20px;
}

.next-btn {
  right: 20px;
}

.image-display {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 20px;
}

.gallery-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.gallery-error {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  min-height: 400px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
  border: 2px dashed #dee2e6;
  position: relative;
  overflow: hidden;
}

.gallery-error::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% { left: -100%; }
  100% { left: 100%; }
}

.error-content {
  text-align: center;
  color: #6c757d;
  z-index: 1;
  position: relative;
  padding: 2rem;
}

.error-icon {
  font-size: 64px;
  display: block;
  margin-bottom: 1.5rem;
  opacity: 0.6;
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.error-text {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 12px 0;
  color: #495057;
}

.error-desc {
  font-size: 16px;
  margin: 0 0 12px 0;
  color: #6c757d;
  line-height: 1.5;
}

.error-solution {
  font-size: 14px;
  margin: 0;
  color: #28a745;
  font-weight: 600;
  padding: 8px 16px;
  background: rgba(40, 167, 69, 0.1);
  border-radius: 8px;
  border: 1px solid rgba(40, 167, 69, 0.2);
}

.gallery-footer {
  padding: 20px 24px;
  border-top: 1px solid #e9ecef;
  background: #f8f9fa;
}

.image-counter {
  display: block;
  text-align: center;
  font-size: 14px;
  color: var(--text-color);
  margin-bottom: 16px;
  font-weight: 600;
}

.thumbnail-container {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
  max-height: 80px;
  overflow-y: auto;
}

.thumbnail {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color 0.3s ease;
  flex-shrink: 0;
}

.thumbnail.active {
  border-color: var(--primary-color);
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail:hover {
  border-color: var(--primary-hover);
}
</style> 